package com.peachcastle.net 
{
	import com.peachcastle.debug.Log;
	
	import com.peachcastle.events.LoaderEvent;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.events.IOErrorEvent;
	

	[Event(name = "loaderitem_complete", type = "com.peachcastle.events.LoaderEvent")]
	[Event(name = "loaderall_complete", type = "com.peachcastle.events.LoaderEvent" )]
	[Event(name = "loader_progress", type = "com.peachcastle.events.LoaderEvent")]
	
	public class QueueLoader extends EventDispatcher
	{
		
		
		private var _loader:Loader = null;
		private var _request:URLRequest = null;
		private var _resource:Array = null;
		private var _index:int = 0;
		
		public function QueueLoader() 
		{
			_resource = [];
			_request = new URLRequest();
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
		}
		
		private function onError(e:IOErrorEvent):void
		{
			Log.debug("QueueLoader onError...", e);
		}
		
		private function onProgress(event:ProgressEvent):void
		{
			var evt:LoaderEvent = new LoaderEvent(LoaderEvent.LOADER_PROGRESS);
			var pro:int = Math.ceil(100 * _index / _resource.length);
			evt.progress = (event.bytesLoaded / event.bytesTotal)*100/_resource.length+pro; 
			dispatchEvent(evt);
		}
		
		private function onComplete(event:Event):void
		{
			var info:LoaderInfo = event.target as LoaderInfo;
			LoaderItem(_resource[_index]).applicate = info.applicationDomain;
			LoaderItem(_resource[_index]).content = info.content;
			
			var evt:LoaderEvent = new LoaderEvent(LoaderEvent.LOADERITEM_COMPLETE);
			evt.item = LoaderItem(_resource[_index]);
			dispatchEvent(evt);
			if (_index < _resource.length - 1)
			{
				_index++;
				start();
			}
			else
			{
				dispatchEvent(new LoaderEvent(LoaderEvent.LOADERALL_COMPLETE));	
			}
			
		}
		
		public function addItem(url:String,name:String):void
		{
			_resource[_resource.length] = new LoaderItem(url, name);
		}
		
		public function start():void
		{
			if (_resource.length < 1) 
			{
				dispatchEvent(new LoaderEvent(LoaderEvent.LOADERALL_COMPLETE));	
				return;
			}
			
			_request.url = LoaderItem(_resource[_index]).url;
			_loader.load(_request, new LoaderContext(false, ApplicationDomain.currentDomain));
					
		}
		
		public function getNameByLibary(name:String):LoaderItem
		{
			for each(var item:LoaderItem in _resource)
			{
				if (item.name == name) return item;
			}
			
			return null;
		}
		
	}

}